<template>
  <div class="document-drafting-page">
    <div class="page-header">
      <h1>智能文书</h1>
      <p>文书起草、合同审查一键完成</p>
    </div>

    <div class="drafting-container">
      <!-- 左侧：功能选择 -->
      <div class="function-panel">
        <div class="function-tabs">
          <div 
            class="tab-item" 
            :class="{ active: activeTab === 'draft' }"
            @click="activeTab = 'draft'"
          >
            <el-icon><EditPen /></el-icon>
            文书起草
          </div>
          <div 
            class="tab-item" 
            :class="{ active: activeTab === 'review' }"
            @click="activeTab = 'review'"
          >
            <el-icon><Document /></el-icon>
            合同审查
          </div>
        </div>

        <!-- 文书起草 -->
        <div v-if="activeTab === 'draft'" class="draft-section">
          <div class="section-title">
            <h3>选择文书类型</h3>
            <p>选择您需要起草的文书类型</p>
          </div>
          
          <div class="document-types">
            <div 
              v-for="type in documentTypes" 
              :key="type.id"
              class="type-card"
              :class="{ selected: selectedType?.id === type.id }"
              @click="selectDocumentType(type)"
            >
              <el-icon class="type-icon">
                <component :is="type.icon" />
              </el-icon>
              <h4>{{ type.name }}</h4>
              <p>{{ type.description }}</p>
            </div>
          </div>

          <div v-if="selectedType" class="draft-form">
            <h3>填写基本信息</h3>
            <el-form :model="draftForm" label-width="100px">
              <el-form-item label="文书标题">
                <el-input v-model="draftForm.title" placeholder="请输入文书标题" />
              </el-form-item>
              <el-form-item label="背景描述">
                <el-input 
                  v-model="draftForm.background" 
                  type="textarea" 
                  :rows="4"
                  placeholder="请详细描述案件背景、争议焦点等信息"
                />
              </el-form-item>
              <el-form-item label="起草目的">
                <el-input 
                  v-model="draftForm.purpose" 
                  type="textarea" 
                  :rows="3"
                  placeholder="请说明起草此文书的目的和预期效果"
                />
              </el-form-item>
              <el-form-item>
                <el-button 
                  type="primary" 
                  @click="generateDocument"
                  :loading="isGenerating"
                  :disabled="!canGenerate"
                >
                  生成文书
                </el-button>
                <el-button @click="resetForm">重置</el-button>
              </el-form-item>
            </el-form>
          </div>
        </div>

        <!-- 合同审查 -->
        <div v-if="activeTab === 'review'" class="review-section">
          <div class="section-title">
            <h3>上传合同文档</h3>
            <p>支持Word、PDF格式，最大10MB</p>
          </div>

          <el-upload
            class="contract-upload"
            drag
            :before-upload="beforeUpload"
            :on-success="handleUploadSuccess"
            :on-error="handleUploadError"
            action="/api/upload"
            accept=".doc,.docx,.pdf"
          >
            <el-icon class="el-icon--upload"><UploadFilled /></el-icon>
            <div class="el-upload__text">
              将文件拖到此处，或<em>点击上传</em>
            </div>
            <template #tip>
              <div class="el-upload__tip">
                只能上传 doc/docx/pdf 文件，且不超过 10MB
              </div>
            </template>
          </el-upload>

          <div v-if="uploadedFile" class="uploaded-file">
            <div class="file-info">
              <el-icon><Document /></el-icon>
              <span>{{ uploadedFile.name }}</span>
              <el-button type="link" @click="removeFile">
                <el-icon><Delete /></el-icon>
              </el-button>
            </div>
            <el-button 
              type="primary" 
              @click="reviewContract"
              :loading="isReviewing"
            >
              开始审查
            </el-button>
          </div>
        </div>
      </div>

      <!-- 右侧：结果展示 -->
      <div class="result-panel">
        <div v-if="!hasResult" class="empty-result">
          <el-icon class="empty-icon"><DocumentCopy /></el-icon>
          <h3>{{ activeTab === 'draft' ? '文书生成结果' : '合同审查结果' }}</h3>
          <p>{{ activeTab === 'draft' ? '请选择文书类型并填写信息后生成' : '请上传合同文档后开始审查' }}</p>
        </div>

        <div v-else class="result-content">
          <div class="result-header">
            <h3>{{ resultTitle }}</h3>
            <div class="result-actions">
              <el-button type="primary" @click="downloadResult">
                <el-icon><Download /></el-icon>
                下载
              </el-button>
              <el-button @click="copyResult">
                <el-icon><CopyDocument /></el-icon>
                复制
              </el-button>
              <el-button type="link" @click="clearResult">
                <el-icon><Delete /></el-icon>
                清空
              </el-button>
            </div>
          </div>
          
          <div class="result-body" v-html="resultContent"></div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { ElMessage } from 'element-plus'

interface DocumentType {
  id: string
  name: string
  description: string
  icon: string
}

const activeTab = ref<'draft' | 'review'>('draft')
const selectedType = ref<DocumentType | null>(null)
const isGenerating = ref(false)
const isReviewing = ref(false)
const uploadedFile = ref<any>(null)
const resultContent = ref('')
const resultTitle = ref('')

// 文书类型
const documentTypes: DocumentType[] = [
  {
    id: 'complaint',
    name: '起诉状',
    description: '民事、行政、刑事起诉状',
    icon: 'Document'
  },
  {
    id: 'answer',
    name: '答辩状',
    description: '针对起诉的答辩文书',
    icon: 'ChatLineRound'
  },
  {
    id: 'appeal',
    name: '上诉状',
    description: '不服一审判决的上诉文书',
    icon: 'Top'
  },
  {
    id: 'lawyer-letter',
    name: '律师函',
    description: '催告、警告、协商函件',
    icon: 'Message'
  },
  {
    id: 'contract',
    name: '合同协议',
    description: '各类合同协议模板',
    icon: 'Tickets'
  },
  {
    id: 'legal-opinion',
    name: '法律意见书',
    description: '专业法律分析意见',
    icon: 'Reading'
  }
]

// 起草表单
const draftForm = ref({
  title: '',
  background: '',
  purpose: ''
})

// 计算属性
const hasResult = computed(() => !!resultContent.value)
const canGenerate = computed(() => 
  selectedType.value && draftForm.value.title && draftForm.value.background
)

// 选择文书类型
const selectDocumentType = (type: DocumentType) => {
  selectedType.value = type
  draftForm.value.title = `${type.name} - ${new Date().toLocaleDateString()}`
}

// 生成文书
const generateDocument = async () => {
  if (!selectedType.value) return
  
  isGenerating.value = true
  
  // 模拟生成过程
  setTimeout(() => {
    const mockContent = generateMockDocument(selectedType.value!, draftForm.value)
    resultContent.value = mockContent
    resultTitle.value = `${selectedType.value!.name} - ${draftForm.value.title}`
    isGenerating.value = false
    ElMessage.success('文书生成成功')
  }, 3000)
}

// 生成模拟文书内容
const generateMockDocument = (type: DocumentType, form: any): string => {
  const templates = {
    complaint: `
      <div class="document-content">
        <h2 style="text-align: center; margin-bottom: 30px;">${form.title}</h2>
        
        <p><strong>原告：</strong>_____________</p>
        <p><strong>被告：</strong>_____________</p>
        
        <h3>诉讼请求：</h3>
        <p>1. 请求法院判令被告_____________；</p>
        <p>2. 请求法院判令被告承担本案诉讼费用。</p>
        
        <h3>事实与理由：</h3>
        <p>${form.background}</p>
        <p>基于上述事实，${form.purpose}</p>
        
        <p>综上所述，原告的诉讼请求合法合理，请求人民法院依法支持。</p>
        
        <p style="text-align: right; margin-top: 40px;">
          此致<br>
          ___人民法院<br><br>
          原告：_____________<br>
          ${new Date().toLocaleDateString()}
        </p>
      </div>
    `,
    'lawyer-letter': `
      <div class="document-content">
        <h2 style="text-align: center; margin-bottom: 30px;">律师函</h2>
        
        <p><strong>致：</strong>_____________</p>
        
        <p>我们是_____________律师事务所律师，受_____________委托，就_____________事宜致函如下：</p>
        
        <h3>基本情况：</h3>
        <p>${form.background}</p>
        
        <h3>法律分析：</h3>
        <p>根据相关法律规定，${form.purpose}</p>
        
        <h3>律师意见：</h3>
        <p>1. 建议贵方立即_____________；</p>
        <p>2. 如贵方在收到本函后___日内仍不履行相关义务，我方将采取进一步法律行动。</p>
        
        <p>特此函告。</p>
        
        <p style="text-align: right; margin-top: 40px;">
          _____________律师事务所<br>
          律师：_____________<br>
          ${new Date().toLocaleDateString()}
        </p>
      </div>
    `
  }
  
  return templates[type.id as keyof typeof templates] || templates.complaint
}

// 重置表单
const resetForm = () => {
  draftForm.value = {
    title: '',
    background: '',
    purpose: ''
  }
  selectedType.value = null
}

// 文件上传前检查
const beforeUpload = (file: File) => {
  const isValidType = ['application/pdf', 'application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'].includes(file.type)
  const isLt10M = file.size / 1024 / 1024 < 10

  if (!isValidType) {
    ElMessage.error('只能上传 PDF、Word 格式的文件!')
    return false
  }
  if (!isLt10M) {
    ElMessage.error('文件大小不能超过 10MB!')
    return false
  }
  return true
}

// 上传成功
const handleUploadSuccess = (response: any, file: any) => {
  uploadedFile.value = file
  ElMessage.success('文件上传成功')
}

// 上传失败
const handleUploadError = () => {
  ElMessage.error('文件上传失败')
}

// 移除文件
const removeFile = () => {
  uploadedFile.value = null
}

// 审查合同
const reviewContract = async () => {
  if (!uploadedFile.value) return
  
  isReviewing.value = true
  
  // 模拟审查过程
  setTimeout(() => {
    const mockReview = generateMockReview(uploadedFile.value.name)
    resultContent.value = mockReview
    resultTitle.value = `合同审查报告 - ${uploadedFile.value.name}`
    isReviewing.value = false
    ElMessage.success('合同审查完成')
  }, 4000)
}

// 生成模拟审查报告
const generateMockReview = (filename: string): string => {
  return `
    <div class="review-content">
      <h2 style="text-align: center; margin-bottom: 30px;">合同审查报告</h2>
      
      <p><strong>文件名称：</strong>${filename}</p>
      <p><strong>审查时间：</strong>${new Date().toLocaleString()}</p>
      <p><strong>审查结果：</strong><span style="color: #e6a23c;">发现 3 处风险点</span></p>
      
      <h3 style="color: #f56c6c;">🔴 高风险条款</h3>
      <div style="background: #fef0f0; padding: 15px; border-left: 4px solid #f56c6c; margin: 10px 0;">
        <p><strong>第3条 违约责任</strong></p>
        <p>问题：违约金比例过高，可能被法院调整</p>
        <p>建议：将违约金比例调整为合同总额的20%以内</p>
      </div>
      
      <h3 style="color: #e6a23c;">🟡 中风险条款</h3>
      <div style="background: #fdf6ec; padding: 15px; border-left: 4px solid #e6a23c; margin: 10px 0;">
        <p><strong>第7条 争议解决</strong></p>
        <p>问题：仲裁条款约定不明确</p>
        <p>建议：明确仲裁机构和仲裁规则</p>
      </div>
      
      <div style="background: #fdf6ec; padding: 15px; border-left: 4px solid #e6a23c; margin: 10px 0;">
        <p><strong>第9条 知识产权</strong></p>
        <p>问题：知识产权归属约定模糊</p>
        <p>建议：明确约定知识产权的归属和使用权限</p>
      </div>
      
      <h3 style="color: #67c23a;">✅ 合规条款</h3>
      <p>其他条款符合法律规定，风险较低。</p>
      
      <h3>总体建议</h3>
      <p>1. 建议修改高风险条款后再签署</p>
      <p>2. 可考虑增加保密条款和不可抗力条款</p>
      <p>3. 建议双方协商确定更明确的履行标准</p>
    </div>
  `
}

// 下载结果
const downloadResult = () => {
  const blob = new Blob([resultContent.value], { type: 'text/html' })
  const url = URL.createObjectURL(blob)
  const a = document.createElement('a')
  a.href = url
  a.download = `${resultTitle.value}.html`
  a.click()
  URL.revokeObjectURL(url)
  ElMessage.success('下载成功')
}

// 复制结果
const copyResult = async () => {
  try {
    await navigator.clipboard.writeText(resultContent.value.replace(/<[^>]*>/g, ''))
    ElMessage.success('复制成功')
  } catch {
    ElMessage.error('复制失败')
  }
}

// 清空结果
const clearResult = () => {
  resultContent.value = ''
  resultTitle.value = ''
  ElMessage.success('已清空结果')
}
</script>

<style lang="scss" scoped>
.document-drafting-page {
  padding: 20px;
  height: calc(100vh - 120px);
  display: flex;
  flex-direction: column;

  .page-header {
    margin-bottom: 20px;
    
    h1 {
      margin: 0 0 8px 0;
      color: #303133;
      font-size: 24px;
    }
    
    p {
      margin: 0;
      color: #606266;
      font-size: 14px;
    }
  }

  .drafting-container {
    flex: 1;
    display: flex;
    gap: 20px;
    min-height: 0;

    .function-panel {
      width: 400px;
      background: #fff;
      border-radius: 8px;
      border: 1px solid #e4e7ed;
      display: flex;
      flex-direction: column;

      .function-tabs {
        display: flex;
        border-bottom: 1px solid #e4e7ed;
        
        .tab-item {
          flex: 1;
          padding: 16px;
          text-align: center;
          cursor: pointer;
          transition: all 0.3s;
          display: flex;
          align-items: center;
          justify-content: center;
          gap: 8px;
          
          &:hover {
            background: #f8f9fa;
          }
          
          &.active {
            background: #409eff;
            color: #fff;
          }
          
          .el-icon {
            font-size: 18px;
          }
        }
      }

      .draft-section, .review-section {
        flex: 1;
        padding: 20px;
        overflow-y: auto;

        .section-title {
          margin-bottom: 20px;
          
          h3 {
            margin: 0 0 8px 0;
            color: #303133;
          }
          
          p {
            margin: 0;
            color: #606266;
            font-size: 14px;
          }
        }

        .document-types {
          display: grid;
          grid-template-columns: 1fr 1fr;
          gap: 12px;
          margin-bottom: 20px;

          .type-card {
            padding: 16px;
            border: 1px solid #e4e7ed;
            border-radius: 6px;
            cursor: pointer;
            transition: all 0.3s;
            text-align: center;
            
            &:hover {
              border-color: #409eff;
              box-shadow: 0 2px 8px rgba(64, 158, 255, 0.15);
            }
            
            &.selected {
              border-color: #409eff;
              background: #f0f9ff;
            }
            
            .type-icon {
              font-size: 24px;
              color: #409eff;
              margin-bottom: 8px;
            }
            
            h4 {
              margin: 0 0 4px 0;
              font-size: 14px;
              color: #303133;
            }
            
            p {
              margin: 0;
              font-size: 12px;
              color: #909399;
            }
          }
        }

        .draft-form {
          h3 {
            margin: 0 0 16px 0;
            color: #303133;
            font-size: 16px;
          }
        }

        .contract-upload {
          margin-bottom: 20px;
          
          :deep(.el-upload-dragger) {
            width: 100%;
            height: 180px;
          }
        }

        .uploaded-file {
          .file-info {
            display: flex;
            align-items: center;
            gap: 8px;
            padding: 12px;
            background: #f8f9fa;
            border-radius: 4px;
            margin-bottom: 16px;
            
            .el-icon {
              color: #409eff;
            }
            
            span {
              flex: 1;
              color: #303133;
            }
          }
        }
      }
    }

    .result-panel {
      flex: 1;
      background: #fff;
      border-radius: 8px;
      border: 1px solid #e4e7ed;
      display: flex;
      flex-direction: column;

      .empty-result {
        flex: 1;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        color: #909399;
        
        .empty-icon {
          font-size: 64px;
          margin-bottom: 16px;
        }
        
        h3 {
          margin: 0 0 8px 0;
          color: #606266;
        }
        
        p {
          margin: 0;
          font-size: 14px;
        }
      }

      .result-content {
        flex: 1;
        display: flex;
        flex-direction: column;

        .result-header {
          padding: 20px;
          border-bottom: 1px solid #e4e7ed;
          display: flex;
          justify-content: space-between;
          align-items: center;
          
          h3 {
            margin: 0;
            color: #303133;
          }
          
          .result-actions {
            display: flex;
            gap: 8px;
          }
        }

        .result-body {
          flex: 1;
          padding: 20px;
          overflow-y: auto;
          
          :deep(.document-content) {
            line-height: 1.8;
            
            h2, h3 {
              color: #303133;
              margin: 20px 0 12px 0;
            }
            
            p {
              margin: 12px 0;
              color: #606266;
            }
          }
          
          :deep(.review-content) {
            line-height: 1.6;
            
            h2, h3 {
              color: #303133;
              margin: 20px 0 12px 0;
            }
            
            p {
              margin: 8px 0;
              color: #606266;
            }
          }
        }
      }
    }
  }
}

@media (max-width: 768px) {
  .document-drafting-page {
    .drafting-container {
      flex-direction: column;
      
      .function-panel {
        width: 100%;
        height: 400px;
      }
    }
  }
}
</style>
